package com.example.gramediamajalahmobile.main;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;

import org.brickred.socialauth.android.DialogListener;
import org.brickred.socialauth.android.SocialAuthAdapter;
import org.brickred.socialauth.android.SocialAuthAdapter.Provider;
import org.brickred.socialauth.android.SocialAuthError;
import org.brickred.socialauth.android.SocialAuthListener;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.example.gramediamajalahmobile.ArticleBean;
import com.example.gramediamajalahmobile.JSONParser;
import com.example.gramediamajalahmobile.R;
import com.example.gramediamajalahmobile.favorite.FavoriteList;
import com.example.gramediamajalahmobile.sqlite.DBHelperFavorite;

public class Detail extends Activity {

	private static final String AR_ID = "id";
	ImageButton gambar, btnAddFav;
	Button btnShare;
	protected DBHelperFavorite dbHelper;
	SocialAuthAdapter adapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.detail);
		Intent in = getIntent();
		String id = in.getStringExtra(AR_ID);
		String link_url = "http://192.168.2.23/codeigniter-restserver-master/index.php/gom/detail?id="
				+ id;
		btnAddFav = (ImageButton) findViewById(R.id.buttonAddFav);
		btnShare = (Button) findViewById(R.id.buttonshare);
		btnShare.setBackgroundResource(R.drawable.iconshare);
		dbHelper = new DBHelperFavorite(this);
		dbHelper.open();
		JSONParser jParser = new JSONParser();
		JSONArray json = jParser.AmbilJson(link_url);

		try {
			for (int i = 0; i < json.length(); i++) {
				JSONObject ar = json.getJSONObject(i);

				TextView title = (TextView) findViewById(R.id.title_d);
				TextView tanggal = (TextView) findViewById(R.id.tanggal);
				TextView view = (TextView) findViewById(R.id.view);
				gambar = (ImageButton) findViewById(R.id.gambar);
				WebView body = (WebView) findViewById(R.id.body);

				final String s_title = ar.getString("title");
				final String s_tanggal = ar.getString("published");
				final String s_view = ar.getString("view");
				final String s_gambar = ar.getString("image_filename");
				final String s_body = ar.getString("body");

				long timestamp = Long.parseLong(s_tanggal) * 1000;
				SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM yyyy");
				String date = sdf.format(timestamp);
				title.setText(s_title);
				loadImage(s_gambar);
				view.setText("view : " + s_view);
				tanggal.setText(date);

				body.loadData(s_body, "text/html", "UTF-8");

				gambar.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						switch (v.getId()) {
						case R.id.gambar:
							setContentView(R.layout.imagezoom);

							// load view
							WebView zoom = (WebView) findViewById(R.id.zoom);
							// (*) this line make uses of the Zoom control
							zoom.getSettings().setBuiltInZoomControls(true);
							zoom.loadUrl(s_gambar);
						}
					}
				});
				btnAddFav.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						ArticleBean article = new ArticleBean();
						article.setTitle(s_title.toString());
						article.setGambar(s_gambar.toString());
						article.setTanggal(s_tanggal.toString());
						article.setView(s_view.toString());

						article.setBody(s_body.toString());
						dbHelper.createFavorite(article);

						Toast.makeText(Detail.this, "telah berhasil disimpan",
								Toast.LENGTH_SHORT).show();

					}
				});

				btnShare.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						adapter = new SocialAuthAdapter(new ResponseListener());

						// Add providers
						adapter.addProvider(Provider.FACEBOOK,
								R.drawable.facebook);
						adapter.addProvider(Provider.TWITTER,
								R.drawable.twitter);
						adapter.addProvider(Provider.LINKEDIN,
								R.drawable.linkedin);
						adapter.addProvider(Provider.YAHOO, R.drawable.yahoo);

						// Providers require setting user call Back url
						adapter.addCallBack(Provider.TWITTER,
								"http://socialauth.in/socialauthdemo/socialAuthSuccessAction.do");
						adapter.addCallBack(Provider.FACEBOOK,
								"http://socialauth.in/socialauthdemo/socialAuthSuccessAction.do");
						adapter.addCallBack(Provider.LINKEDIN,
								"http://socialauth.in/socialauthdemo/socialAuthSuccessAction.do");
						adapter.addCallBack(Provider.YAHOO,
								"http://socialauth.in/socialauthdemo/socialAuthSuccessAction.do");

						// Enable Provider
						adapter.enable(btnShare);
						// startActivity(inShare);
					}
				});

			}
		} catch (JSONException e) {
			e.printStackTrace();

		}

	}

	Bitmap bitmap;

	void loadImage(String image_location) {
		URL imageURL = null;
		try {
			imageURL = new URL(image_location);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		try {
			HttpURLConnection connection = (HttpURLConnection) imageURL
					.openConnection();
			connection.setDoInput(true);
			connection.connect();
			InputStream inputStream = connection.getInputStream();
			// Convert to bitmap
			bitmap = BitmapFactory.decodeStream(inputStream);
			gambar.setImageBitmap(bitmap);
			// imaged.setBitmap(bitmap);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private final class ResponseListener implements DialogListener {
		@Override
		public void onComplete(Bundle values) {

			Log.d("ShareButton", "Authentication Successful");

			// Get name of provider after authentication
			final String providerName = values
					.getString(SocialAuthAdapter.PROVIDER);
			Log.d("ShareButton", "Provider Name = " + providerName);
			Toast.makeText(Detail.this, providerName + " connected",
					Toast.LENGTH_LONG).show();

			// Please avoid sending duplicate message. Social Media Providers
			// block duplicate messages.

			// Share via twitter
			if (providerName.equalsIgnoreCase("share twitter")) {
				// Use your own code here
				Intent twittIntent = new Intent(Intent.ACTION_SENDTO,
						Uri.fromParts("twitto", "rerenietha@rocketmail.com",
								null));
				twittIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
						"twitt");
				File file = new File(
						Environment
								.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
						"image5964402.png");
				Uri uri = Uri.fromFile(file);
				twittIntent.putExtra(Intent.EXTRA_STREAM, uri);
				startActivity(Intent.createChooser(twittIntent, "twitt"));
			}
		}

		@Override
		public void onError(SocialAuthError error) {
			Log.d("ShareButton", "Authentication Error: " + error.getMessage());
		}

		@Override
		public void onCancel() {
			Log.d("ShareButton", "Authentication Cancelled");
		}

		@Override
		public void onBack() {
			Log.d("Share-Button", "Dialog Closed by pressing Back Key");
		}

	}

	// To get status of message after authentication
	private final class MessageListener implements SocialAuthListener<Integer> {
		@Override
		public void onExecute(String provider, Integer t) {
			Integer status = t;
			if (status.intValue() == 200 || status.intValue() == 201
					|| status.intValue() == 204)
				Toast.makeText(Detail.this, "Message posted on " + provider,
						Toast.LENGTH_LONG).show();
			else
				Toast.makeText(Detail.this,
						"Message not posted on " + provider, Toast.LENGTH_LONG)
						.show();
		}

		@Override
		public void onError(SocialAuthError e) {

		}
	}

}
